package ntd.protocol.context;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import ntd.protocol.bo.Ntd212BO;
import ntd.tool.abnormal.ComAbnormal;

@Data
public class Context212 {

    // 字符
    private static final String toe = "##";

    // 包尾（"\r\n"）
    private static final String msgEnd = "\r\n";

    // 报文串
    private String msg;

    // 数据段长度 - 10进制，长度4
    private Integer dataLen;

    // 数据串 - 字符
    private String data;

    // crc校验 - 16进制，长度4
    private String crcVerify;

    // 数据解析结果
    private Ntd212BO ntd212BO;

    public static Context212 parse(String msg) {
        Context212 context212 = new Context212();
        context212.setMsg(msg);
        verify(context212);
        return context212;
    }

    private static void verify(Context212 context212) {
        String msg = context212.getMsg();
        if (StrUtil.isBlank(msg)) {
            throw new ComAbnormal("212解析异常，报文不能为空！");
        }
        if (!msg.startsWith(toe)) {
            throw new ComAbnormal("212解析异常，包头标识错误！");
        }
        if (!msg.endsWith(msgEnd) && !msg.endsWith("\n")) {
            throw new ComAbnormal("212解析异常，包尾标识错误！");
        }
        String content = "";
        if (msg.endsWith(msgEnd)) {
            content = StrUtil.subBetween(msg, toe, msgEnd);
        }
        if (msg.endsWith("\n")) {
            content = StrUtil.subBetween(msg, toe, "\n");
        }
        int endIndex = StrUtil.lastIndexOfIgnoreCase(content, "&&") + 2;
        context212.setDataLen(Convert.toInt(StrUtil.sub(content, 0, 4)));
        context212.setCrcVerify(StrUtil.sub(content, -endIndex, 0));
        context212.setData(StrUtil.sub(content, 4, endIndex));
//        if (context212.getDataLen() != context212.getData().length()) {
//            throw new Exception("212解析异常，数据包长度错误！");
//        }
        // crc校验
    }
}
